package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 登录鉴权
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取当前的uri
        String uri = request.getURI().getPath();
        if (uri.contains("login_auth")) {
            //当前请求为登录->放行
            return chain.filter(exchange);
        }

        //获取token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            //token不存在 响应错误码401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //token存在
        //解析token是否有效  ->>> -1：有效，0：有效，1：过期，2：过期
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int isEnabled = AppJwtUtil.verifyToken(claimsBody);
        if (isEnabled == -1 || isEnabled == 0) {
            //有效

            //获取token解析后的用户id
            Object userId = claimsBody.get("id");
            //在header中添加新的信息
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();
            return chain.filter(exchange);
        }

        //token无效
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
